package com.webcams.core.location;

import java.util.ArrayList;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class ResortLocationManager implements LocationListener {

	private LocationManager locationManager;
	private static ResortLocationManager instance;
	private String provider;
	private ArrayList<LocationManagerListener> listeners;

	private Location mLastLocation;

	public static ResortLocationManager getInstance(Context c) {
		if(instance == null){
			instance = new ResortLocationManager(c);
		}
		return instance;
	}

	private ResortLocationManager(Context context){
		listeners = new ArrayList<LocationManagerListener>();
		locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		enable();
		setBetterLocation();
	}

	private void setBetterLocation() {
		provider = locationManager.getBestProvider(new Criteria(), false);
		Location tempLocation = locationManager.getLastKnownLocation(provider);
		if(tempLocation != null) {
			if(mLastLocation != null && mLastLocation.getTime() > tempLocation.getTime())
				return;
			mLastLocation = tempLocation;
		}
	}

	private void enable(){
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
		locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this);
	}

	private void disable(){
		locationManager.removeUpdates(this);
	}

	private void spreadListeners() {
		for(LocationManagerListener l : listeners) {
			l.onLocationChanged(mLastLocation);
		}
	}


	public void addListener(LocationManagerListener lml){
		if(listeners.size() == 0) {
			this.enable();
			setBetterLocation();
			onLocationChanged(mLastLocation);
		}
		listeners.add(lml);
	}

	public void removeListener(LocationManagerListener lml) {
		listeners.remove(lml);
		if(listeners.size() == 0) {
			this.disable();
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		Log.v("DEBUG", "!!Location changed "+location);
		if(mLastLocation != null && mLastLocation.getTime() >= location.getTime()) {
			return;
		}
		mLastLocation = location;
		spreadListeners();
	}

	@Override
	public void onProviderDisabled(String provider) {
		Log.v("DEBUG", "!!provider disabled : "+provider);

	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.v("DEBUG", "!!provider enabled : "+provider);

		setBetterLocation();
		onLocationChanged(mLastLocation);

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {		
	}

	public Location getLastLocation() {
		return mLastLocation;
	}	
}
